<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Functions
{

	/**
	 * Constructor
	 */
    function Functions()
    {
        $this->obj =& get_instance();
	
    }
	// --------------------------------------------------------------------

    	/**
	 * Get Country List
	 *
	 * This function queries database table "country" with name of the country in assecending order
	 * and returns array of country country id and country name
	 *
	 * @access	public
	 * @return	array
	 */
	function getCountryList($status = 'Active'){

		$query = "SELECT * FROM `country_master` ";
		if($status != 'all')
		{
			$query.=" WHERE `status` = '".$status."'";
		}
		$query.=" ORDER BY `country_name` ='United States' DESC ,`country_name` ASC";

		$recordSet = $this->obj->db->query($query);
		if($recordSet->num_rows() > 0)
		{
           	$rs = array();
			$isEscapeArr = array();
			foreach ($recordSet->result_array() as $row)
			{
				foreach($row as $key=>$val){
					if(!in_array($key,$isEscapeArr)){
						$recordSet->fields[$key] = outputEscapeString($val);
					}
				}
				$rs[] = $recordSet->fields;
			}
			return $rs;
		}
		else
		{
			return "";
		}
	}
	// --------------------------------------------------------------------


		// --------------------------------------------------------------------

	/**
	 * Get Content for Page
	 *
	 * This function takes the page-name from the segment of url
	 * and queries database table "contents"
	 * Returns the content and other values such as page-title, meta-tags etc for the page in an array
	 *
	 * @access	public
	 * @param	string
	 * @return	array
	 */
	function getContent($url)
    {
	    $query = "SELECT * FROM ".CONTENTS."
				  WHERE `url` = '".$url."' ";
		$recordSet = $this->obj->db->query($query);

		$rs = false;
		if ($recordSet->num_rows() > 0)
        {
           	$rs = array();
			$isEscapeArr = array('content');
			foreach ($recordSet->result_array() as $row)
			{
				foreach($row as $key=>$val){
					if(!in_array($key,$isEscapeArr)){
						$recordSet->fields[$key] = outputEscapeString($val);
					}else{
						$recordSet->fields[$key] = outputEscapeString($val,'HTML');
					}
				}
				$rs = $recordSet->fields;
			}
        }else{
        	$rs['title']				=	GLOBAL_SITE_NAME;
        	$rs['meta_title']			=	GLOBAL_META_TITLE;
        	$rs['meta_keywords']		=	GLOBAL_META_KEYWORDS;
        	$rs['meta_description']		=	GLOBAL_META_DESCRIPTION;
        	$rs['content']				=	false;
        }
		return $rs;
    }
	// --------------------------------------------------------------------
	
    /*
     * Function used For Fetching Data
    * param $id string passing id
    * param $table string passing db table name
    * param $query array passing db fields name
    * param $fetch_key string passing db matching field name
    * purpose to Fetch a Single data row
    */
    
    function getSingle($id,$table,$query=false,$fetch_key='',$isEscapeArr= array())
    {
    	if(!empty($query) && is_array($query))
    		$query_string = implode(",",$query);
    	else
    		$query_string = '*';
    	
    	
    	if(!empty($fetch_key))
    		$fetch_key = $fetch_key;
    	else 
    		$fetch_key = 'id';
    
    	$sql = "SELECT ".$query_string." FROM ".$table." WHERE $fetch_key = ".$id;
    	$recordSet = $this->obj->db->query($sql);
    
    	$rs = false;
    	if ($recordSet->num_rows() > 0)
    	{
    		$rs = array();
    		foreach ($recordSet->result_array() as $row)
    		{
    			foreach($row as $key=>$val){
    				if(!in_array($key,$isEscapeArr)){
    					$recordSet->fields[$key] = outputEscapeString($val);
    				}else{
    					$recordSet->fields[$key] = outputEscapeString($val,'TEXTAREA');
    				}
    			}
    			$rs[] = $recordSet->fields;
    		}
    	}
    	return $rs;
    }
    
    // --------------------------------------------------------------------
    

	/**
	 * Checks user for page access
	 *
	 * This function takes the page-name and checks for user authenticity
	 * Returns true if user is authentic
	 * Redirects to user login page if user is not authentic
	 *
	 * @access	public
	 * @param	string
	 * @return	bool
	 */
	function checkUser($section_name)
	{
		$UserID = $this->obj->nsession->userdata('member_session_id');
		if(!$UserID)
		{
			$cookie = array(
				'name' => 'fe_referer_path',
				'value' => $section_name,
				'expire' => '86500',
				'domain' => '',
				'path' => '/',
				'prefix' => '',
			);
			set_cookie($cookie);
			redirect(base_url().'member/');
		}
		return true;
	}
	// --------------------------------------------------------------------

	/**
	 * Checks user for page access
	 *
	 * This function takes the page-name and checks for user authenticity for admin section
	 * Returns true if user is authentic
	 * Redirects to user login page if user is not authentic
	 *
	 * @access	public
	 * @param	string
	 * @return	bool
	 */
	function checkAdmin($section_name)
	{
		$UserID = $this->obj->nsession->userdata('user_session_id');
		$UserRole = $this->obj->nsession->userdata('user_session_role'); 
       	if(!$UserID)
		{
				$cookie = array(
				'name' => 'admin_referer_path',
				'value' => $section_name,
				'expire' => '86500',
				'domain' => '',
				'path' => '/',
				'prefix' => '',
			);
            set_cookie($cookie);
			redirect(base_url().'login/');
			exit;
		}
		return true;
	}
	
	function checkAuthAdmin($section_name)
	{
		$UserID = $this->obj->nsession->userdata('user_session_id');
		$UserRole = $this->obj->nsession->userdata('user_session_role'); 
       	if(!$UserID || $UserRole !='S')
		{
				$cookie = array(
				'name' => 'admin_referer_path',
				'value' => $section_name,
				'expire' => '86500',
				'domain' => '',
				'path' => '/',
				'prefix' => '',
			);
            set_cookie($cookie);
			redirect(base_url().'login/');
			exit;
		}
		return true;
	}
	function checkLogin()
	{
		$UserID = $this->obj->nsession->userdata('member_session_id');
		if(!$UserID){
			redirect(base_url().'member/index');
			exit();
		}
		return true;
	}

	function getNameTable($table,$col,$field='',$value='')
	{
		$query="SELECT ".$col." FROM ".$table." where 1 ";
		if($field!='' && $value!='')
		{
		 	$query.="AND ".$field."='".$value."' ";
		}
		
		$recordSet = $this->obj->db->query($query);
		if($recordSet->num_rows() > 0)
		{
			$row = $recordSet->row_array();
			return $row[$col];
		}
		else
		{
			return "";
		}
	}



	function existRecords($table,$field_name,$field_value,$pk,$pk_value=0,$field_name1="",$field_value1="")
	{
		
		$query="SELECT COUNT(".$pk.") as CNT FROM ".$table." where ".$field_name."='".$field_value."' ";
		
		if($field_name1!="" && $field_value1!="")
		{
		$query.=" AND ".$field_name1."='".$field_value1."' ";
		}
		if($pk_value){
			$query.=" AND ".$pk."!='".$pk_value."'";
		}

		$recordSet = $this->obj->db->query($query);
		if($recordSet->num_rows() > 0)
		{
			$row = $recordSet->row();
			return $row->CNT;
		}
		else
		{
			return "";
		}
	}
	
	function unique_Category($table,$field_name,$field_value,$pk,$pk_value=0,$paging_id,$paging_table)
	{
	    $query="SELECT GROUP_CONCAT(DISTINCT ".$paging_id.") as category_id FROM ".$paging_table." WHERE $paging_id != '$pk_value'";
	    $recordSet = $this->obj->db->query($query);
	    $RECord_Set = $recordSet->result();
	    $CategoRy_id = $RECord_Set[0]->category_id;
	    $field_value;
	    if(!empty($CategoRy_id)){
		 $query="SELECT *  FROM ".$table." WHERE id IN ($CategoRy_id) AND category_name = '".$field_value."'";
		$recordSet = $this->obj->db->query($query);
		$count  = $recordSet->num_rows();
		if($count > 0)
		{
			return $count;
		}
		else
		{
			return "";
		}
	    }
	    else{
		return "";
	    }
	     
		
	}

	function generateUrl($table,$field_name,$field_value,$pk,$pk_value=0){
		$field_value = ereg_replace("[^A-Za-z0-9-]", "", str_replace(array(" "), '-', strtolower($field_value)));

		$existRecords = $this->existRecords($table,$field_name,$field_value,$pk,$pk_value);

		if ($existRecords>0)
		{
			for ($i = 1; $i < 100; $i++)
			{
				$existRecords = $this->existRecords($table,$field_name,$field_value."-".$i,$pk,$pk_value);
				if (!$existRecords)
				{
					$field_value = $field_value."-".$i;
					break;
				}
			}
		}

		$url = strtolower(str_replace("--","-",$field_value));

		return $url;
	}


	function getListTable($table_name, $field='',$value='',$orderfield='',$ordertype='ASC')
	{
		$sql = "SELECT * FROM `".$table_name."` WHERE 1" ;
		if($field != '' && $value!=''){
			$sql.=" AND `".$field."`='".$value."'";
		}
		if($orderfield != ''){
			$sql.=" ORDER BY `".$orderfield."` ".$ordertype."";
		}
		$recordSet = $this->obj->db->query($sql);

		$rs = false;
		if ($recordSet->num_rows() > 0)
        {
           	$rs = array();
			$isEscapeArr = array();
			foreach ($recordSet->result_array() as $row)
			{
				foreach($row as $key=>$val){
					if(!in_array($key,$isEscapeArr)){
						$recordSet->fields[$key] = outputEscapeString($val);
					}
				}
				$rs[] = $recordSet->fields;
			}
        }
		else
		{
			return false;
		}
		return $rs;
	}
	
	function emailOrderTemplate($body='',$footer='',$path='')
	{
		$template = '<style>p{line-height:15px; font:Arial, Helvetica, sans-serif; font-size: 13px; } </style>
		<table width="802px" border="0" cellpadding="0" cellspacing="0" style="border:#CCCCCC 1px solid; padding:0px; color:#000000; font:normal 12px Arial, Helvetica, sans-serif;">
		<tr>
		<td align="left" style="padding:20px;">##EMAIL_BODY##</td>
		</tr>
		
		</table>
		';
		$email_body = str_replace(array("##EMAIL_BODY##","##EMAIL_FOOTER##","##SITEPATH##"),array($body,$footer,$path),$template);
	
		return $email_body;
	}

	function emailTemplate($body='',$footer='',$path='')
	{
		$template = '<style>p{line-height:15px; font:Arial, Helvetica, sans-serif; font-size: 13px; } </style>
					<table width="984px" border="0" cellpadding="0" cellspacing="0" style="border:#CCCCCC 1px solid; padding:0px; color:#000000; font:normal 12px Arial, Helvetica, sans-serif;">
					  <tr>
						<td align="left" style="padding:20px;">##EMAIL_BODY##</td>
					  </tr>
					  <tr>
						<td align="left" style="padding:20px;">##EMAIL_FOOTER##</td>
					  </tr>
					  <tr>
						<td height="90" align="left" class="block" style="padding-left:20px; margin-left:20px;">
							<h1 style="background:no-repeat scroll 0 0 transparent; float: left;height: 25px;margin: 0 10px 0 0; width: 222px;"><a href="##SITEPATH##" title="Logo" ><img src="##SITEPATH##uploads/logo_image/logo.png" width=""></a></h1>
    						<div style="border-left: 1px solid #737B7D; color: #444F51; float: left; font: 14px Arial,Helvetica,sans-serif; padding: 4px 4px 4px 11px;"></div>
						</td>
					  </tr>
					</table>
					';
		$email_body = str_replace(array("##EMAIL_BODY##","##EMAIL_FOOTER##","##SITEPATH##"),array($body,$footer,$path),$template);

		return $email_body;
	}
 
	function send_email($to_email,$template_code,$search_text=array(),$replace_text=array(),$subject='',$name='',$email='',$cc,$bcc)
	{
		$sql = "SELECT from_name, from_email, subject, email_body FROM ".EMAIL_TEMPLATE_SETTING." WHERE template_code = '".$template_code."'" ; //echo $sql;
	
		$recordSet = $this->obj->db->query($sql);
	
		$rs = false;
		if ($recordSet->num_rows() > 0)
		{
			$rs = array();
			$isEscapeArr = array('email_body');
			foreach ($recordSet->result_array() as $row)
			{
				foreach($row as $key=>$val){
					if(!in_array($key,$isEscapeArr)){
						$recordSet->fields[$key] = outputEscapeString($val);
					}else{
						$recordSet->fields[$key] = outputEscapeString($val,"TEXTAREA");
					}
				}
				$rs = $recordSet->fields;
			}
			if(count($search_text)>0){
				$message = str_replace($search_text,$replace_text,$rs['email_body']);
			}else{
				$message = $rs['email_body'];
			}
	
			$from_email	=$rs['from_email'];
			$from_name	=$rs['from_name'];
			$this->obj->email->from($from_email,$from_name);
			$this->obj->email->to($to_email);
			if($cc){
			    $this->obj->email->cc($cc);
			}
			if($bcc){
			    $this->obj->email->bcc($bcc);
			}
			$this->obj->email->set_mailtype('html');
			$this->obj->email->subject($rs['subject']);
	
			$path 		=  front_base_url();
			$footer	 	=  nl2br(GLOBAL_EMAIL_SIGNATURE);
			$emailBody = $this->emailTemplate($message,$footer,$path);
			$this->obj->email->message($emailBody);
			$this->obj->email->send();
			return true;
		}
		else
		{
			return false;
		}
		exit;
	}
	// --------------------------------------------------------------------
	function getGlobalInfo($field_key)
	{
		$sql = "SELECT field_value FROM ".GLOBALCONFIG." WHERE field_key = '".$field_key."'" ;
		$recordSet = $this->obj->db->query($sql);

		$rs = false;
		if ($recordSet->num_rows() > 0)
        {
 			$isEscapeArr = array('global_email_signatur','global_company_info');
			foreach ($recordSet->result_array() as $row)
			{
				foreach($row as $key=>$val){
					if(!in_array($key,$isEscapeArr)){
						$rs = outputEscapeString($val);
					}else{
						$rs = outputEscapeString($val,"HTML");
					}
				}
			}
        }
        return $rs;

	}

   // --------------------------------------------------------------------

   /* function get_banner($positon,$lmit='0'){
	  
	  
	    $query = " select a.image_name from ".BANNERIMAGEGALLERY." as a , ".BANNERCATEGORY." as b where a.cat_id = b.id AND b.category_name = '$positon' ";
	    if($lmit != '0'){
		
		$query .=" LIMIT 0 , $lmit ";
	    }
	$banners = $this->obj->db->query($query);
	$result_banner = $banners->result();
	
	return $result_banner;
	
    }*/

}

// END Functions Class

/* End of file functions.php */
/* Location: ./system/libraries/functions.php */